package com.example.shirotest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.shirotest.entry.Result;
import com.example.shirotest.entry.Role;
import com.example.shirotest.entry.Sites;
import com.example.shirotest.entry.User;
import com.example.shirotest.mapper.ResultMapper;
import com.example.shirotest.mapper.SitesMapper;
import com.example.shirotest.service.ResultService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ResultServiceImpl extends ServiceImpl<ResultMapper, Result> implements ResultService {

    @Autowired
    ResultMapper resultMapper;

    @Autowired
    SitesMapper sitesMapper;

    @Override
    public PageInfo<Result> selectByPage(Integer page, Integer pagesize, String orderby,Integer sid,String keywords) {
        PageHelper.startPage(page,pagesize,orderby);
        /*List<Result> pages = null;
        if(sid>0){
            pages = resultMapper.findPageBySid(sid);
        }else{
            pages = resultMapper.findPage();
        }*/

        QueryWrapper<Result> wrapper = new QueryWrapper<>();
        if(sid>0) {
            wrapper.eq("sid", sid);
        }
        if(!keywords.isEmpty()) {
            wrapper.like("title", keywords);
        }

        wrapper.orderByDesc("id");

        List<Result> results = resultMapper.selectList(wrapper);

        PageInfo pageInfo = new PageInfo<Result>(results);

        //角色字段提取
        if(pageInfo.getTotal()>0) {
            Map<Integer, Sites> allRoles = getAllSites();
            List<Result> list = pageInfo.getList();
            list.forEach(vo -> vo.setSidstr(allRoles.get(vo.getSid()).getTitle()));
        }

        return pageInfo;
    }

    //获取数据源信息
    public Map<Integer, Sites> getAllSites() {
        QueryWrapper<Sites> wrapper = new QueryWrapper<>();
        wrapper.gt("id",0);
        List<Sites> roleList = sitesMapper.selectList(wrapper);

        Map<Integer,Sites> roleMap = new HashMap<>();
        roleList.forEach(item->roleMap.put(item.getId(), item));

        return roleMap;
    }

}
